<?php

namespace App\Http\Controllers;

use App\Library\AuthenticatedUser;
use App\Library\SysMessages;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
    use SysMessages, AuthenticatedUser;

    protected $request;

    protected $uid = 0;
    protected $username = '';
    protected $user;
    protected $data = [
        'uid'=>0,
        'username'=>'',
    ];

    /**
     * Controller constructor.
     */
    function __construct(Request $request)
    {
        $this->request = $request;
        $this->middleware(function (Request $req, $next){
            if (Auth::check()) {
                $this->user = Auth::user();
                $this->uid  = $this->user->uid;
                $this->username = $this->user->username;
                $this->assign([
                    'uid'=>$this->uid,
                    'username'=>$this->username,
                ]);
            }
            return $next($req);
        });
    }

    /**
     * @param array $array
     * @param bool $replace
     * @param string $prefix
     * @return $this
     */
    protected function assign($array = [], $replace = true, $prefix=''){
        foreach ($array as $key=>$value) {
            if (is_string($key)) {
                if ($replace) {
                    $this->data[$prefix.$key] = $value;
                } else {
                    if (!array_key_exists($key, $this->data)){
                        $this->data[$key] = $value;
                    }
                }
            }
        }
        return $this;
    }

    /**
     * @param $view
     * @param array $data
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    protected function view($view, $data = []) {
        if (is_array($data) && !empty($data)) $this->assign($data);
        return view($view, $this->data);
    }

    /**
     * @return bool
     */
    protected function isOnSubmit(){
        return ($this->request->post('formsubmit') === 'yes');
    }
}
